﻿using HuiZe.education.Model;
using HuiZe.education.Resource.Controls;
using HuiZe.education.ViewModel;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;

namespace HuiZe.education.View
{
    /// <summary>
    /// PlanLessonView.xaml 的交互逻辑
    /// </summary>
    public partial class PlanLessonView : UserControl
    {
        PlanLessonViewModel planModel { get; set; }

        public PlanLessonView()
        {
            InitializeComponent();
            Loaded += ResourceView_Loaded;
            images.Drop += Images_Drop;
            images.PreviewMouseMove += Images_PreviewMouseMove;
            IsVisibleChanged += PlanLessonView_IsVisibleChanged;
            PART_AttendClass.Click += PART_AttendClass_Click;
            PART_LessonHomeView.Click += PART_LessonHomeView_Click;
        }

        void PART_AttendClass_Click(object sender, RoutedEventArgs e)
        {
            if (images.Children.Count > 1)
            {
                if (!planModel.ShowDialogView_Ethan("退出将不保存当前备课数据，是否确定退出?"))
                    return;
            }

            images.Children.Clear();
            planModel.ResourceCount = 0;
            planModel.BkName = string.Empty;
            planModel.CurrentParentName = string.Empty;
            planModel.CurrentCategoryName = string.Empty;
            planModel.EthanMyPackageList = new List<resCourseListChildModel>();
            planModel.NavChangedComand.Execute("AttendClass");
        }

        void PART_LessonHomeView_Click(object sender, RoutedEventArgs e)
        {
            if (images.Children.Count > 1)
            {
                if (!planModel.ShowDialogView_Ethan("退出将不保存当前备课数据，是否确定退出?"))
                    return;
            }

            images.Children.Clear();
            planModel.ResourceCount = 0;
            planModel.BkName = string.Empty;
            planModel.CurrentParentName = string.Empty;
            planModel.CurrentCategoryName = string.Empty;
            planModel.EthanMyPackageList = new List<resCourseListChildModel>();
            planModel.NavChangedComand.Execute("LessonHomeView");
        }

        void Images_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var _pos = e.GetPosition(images);
                HitTestResult _result = VisualTreeHelper.HitTest(images, _pos);
                if (_result == null)
                    return;

                var _item = FindVisualParent<PART_MyLesson_Item>(_result.VisualHit);
                if (_item == null) return;

                DataObject _data_obj = new DataObject(_item);
                DragDrop.DoDragDrop(images, _data_obj, DragDropEffects.Move);
            }
        }

        void Images_Drop(object sender, DragEventArgs e)
        {
            var _pos = e.GetPosition(images);
            HitTestResult _result = VisualTreeHelper.HitTest(images, _pos);
            if (_result == null)
                return;

            var _src = e.Data.GetData(typeof(PART_MyLesson_Item)) as PART_MyLesson_Item;
            if (_src == null) return;

            var _des = FindVisualParent<PART_MyLesson_Item>(_result.VisualHit);
            if (_des == null) return;

            if (ReferenceEquals(_des, _src)) return;

            int _index = images.Children.IndexOf(_des);
            images.Children.Remove(_src);
            images.Children.Insert(_index, _src);
        }

        private void ResourceView_Loaded(object sender, RoutedEventArgs e)
        {
            PlanLessonViewModel planLessoniewModel = DataContext as PlanLessonViewModel;
            planModel = planLessoniewModel;
            planLessoniewModel.planLessonView = this;

            if (planLessoniewModel.IsShowingSelectedBackageItem)
            {
                planLessoniewModel.IsShowingSelectedBackageItem = false;
                var _list = planLessoniewModel.GetResDetailData();
                images.Children.Clear();
                UpdateImg5(_list);
            }
            else
            {
                if (planLessoniewModel.IsNewBuilding)
                {
                    planLessoniewModel.IsNewBuilding = false;

                    images.Children.Clear();
                    planLessoniewModel.BkName = string.Empty;
                    planLessoniewModel.EthanMyPackageList = new List<resCourseListChildModel>();
                }

                planLessoniewModel.ShowResDetailId = string.Empty;
                planLessoniewModel.CurrentEditResDetailID = 0;
                planLessoniewModel.SelectChapterCommand.Execute("SelectChapterView");
            }

            AppendAddResourceButton();

            //planLessoniewModel.CategoryCourseChildList1.Clear();
            //planLessoniewModel.MyCollectResourceList1.Clear();
        }

        private void PlanLessonView_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                this.BeginAnimation(OpacityProperty, (DoubleAnimation)FindResource("doubleAnimation"));
            }
        }

        private void YCButton_Click(object sender, RoutedEventArgs e)
        {
            if (images.Children.Count > 51)
            {
                planModel.ShowDialogView("资源最多只能选择 50个!");
                return;
            }

            PlanLessonViewModel planLessonView = DataContext as PlanLessonViewModel;
            if (planLessonView.EditClassResource())
            {
                //BkText.Text = "";
                //images.Children.Clear();
                planModel.BkName = string.Empty;
                planModel.CurrentParentName = string.Empty;
                planModel.CurrentCategoryName = string.Empty;
                planModel.NavChangedComand.Execute("AttendClass");
            }
        }

        private void CustomButton_Click(object sender, RoutedEventArgs e)
        {
            if (images.Children.Count > 4) return;

            PlanLessonViewModel model = DataContext as PlanLessonViewModel;
            string fileName = model.SelectAllFile(2 * 1024);
            if (string.IsNullOrEmpty(fileName)) return;
            CustomButton customButton = new CustomButton()
            {
                Template = (ControlTemplate)FindResource("selectedImageTemplate"),
                ImageSource = new BitmapImage(new Uri(fileName)),
                Width = 90,
                Margin = new Thickness(0, 0, 10, 0),
            };

            images.Children.Add(customButton);
            model.SetImagesPath(fileName);
        }

        public void UpdateImg(List<resCourseListChildModel> list)
        {
            if (list != null)
            {
                //tip0.Visibility = Visibility.Collapsed;
                //tip1.Visibility = Visibility.Visible;
                //images.Children.Clear();
                foreach (var item in list)
                {
                    //WrapPanel stack = new WrapPanel
                    //{
                    //    Orientation = Orientation.Vertical,
                    //    Width = 150,
                    //    Height = 150,
                    //    HorizontalAlignment = HorizontalAlignment.Left,
                    //    Margin=new Thickness(0,0,0,0)
                    //};
                    //Image image = new Image
                    //{
                    //    Source = new BitmapImage(new Uri(item.file)),
                    //    //Name= item.name,
                    //    Width = 100,
                    //    Height = 120

                    //};


                    //CustomButton customButton = new CustomButton()
                    //{
                    //    Template = (ControlTemplate)FindResource("selectedImageTemplate2"),
                    //    ImageSource = new BitmapImage(new Uri(item.cover)),
                    //    Width = 180,
                    //    Height = 180,
                    //    BkResId = item.id.ToString(),
                    //    BkzyType = 0,
                    //    //Margin = new Thickness(-10,0,0,0),
                    //    Content = item.resources_name
                    //};
                    //customButton.MouseDoubleClick += CustomButtonDouble_Click;
                    //customButton.PreviewMouseUp += PageManage_PreviewMouseUp;

                    ////Label lb = new Label
                    ////{
                    ////    Content = item.resources_name,
                    ////    HorizontalAlignment = HorizontalAlignment.Center
                    ////};
                    ////stack.Children.Add(customButton);
                    //// stack.Children.Add(lb);
                    //images.Children.Add(customButton);
                    //planModel.ResourceCount++;

                    PART_MyLesson_Item _item_mylesson = new PART_MyLesson_Item();
                    _item_mylesson.DeleteCallback = DeleteLessonMedia;
                    _item_mylesson.SelectCallback = ShowLessonMedia;
                    _item_mylesson.Data = item;
                    images.Children.Add(_item_mylesson);
                    planModel.ResourceCount++;
                }

                AppendAddResourceButton();
            }
        }

        public void UpdateImg2(List<resBKCategoryCourseChildModel> list)
        {
            if (list != null)
            {
                //tip0.Visibility = Visibility.Collapsed;
                //tip1.Visibility = Visibility.Visible;
                //images.Children.Clear();
                foreach (var item in list)
                {
                    //StackPanel stack = new StackPanel
                    //{

                    //    Width = 100,
                    //    Height = 150,
                    //    HorizontalAlignment = HorizontalAlignment.Left

                    //};
                    //Image image = new Image
                    //{
                    //    Source = new BitmapImage(new Uri(item.file)),
                    //    //Name= item.name,
                    //    Width = 100,
                    //    Height = 120

                    //};
                    //Label lb = new Label
                    //{
                    //    Content = item.resources_name,
                    //    HorizontalAlignment = HorizontalAlignment.Center
                    //};
                    //stack.Children.Add(image);
                    //stack.Children.Add(lb);

                    //WrapPanel stack = new WrapPanel
                    //{
                    //    Orientation = Orientation.Vertical,
                    //    Width = 170,
                    //    Height = 150,
                    //    HorizontalAlignment = HorizontalAlignment.Left,
                    //    Margin = new Thickness(10, 0, 0, 0)
                    //};
                    //Image image = new Image
                    //{
                    //    Source = new BitmapImage(new Uri(item.file)),
                    //    //Name= item.name,
                    //    Width = 100,
                    //    Height = 120

                    //};


                    CustomButton customButton = new CustomButton()
                    {
                        Template = (ControlTemplate)FindResource("selectedImageTemplate2"),
                        ImageSource = new BitmapImage(new Uri(item.image)),
                        Width = 180,
                        Height = 180,
                        BkResId = item.id.ToString(),
                        BkzyType = 1,
                        //Margin = new Thickness(-10,0,0,0),
                        Content = item.resources_name
                    };
                    customButton.MouseDoubleClick += CustomButtonDouble_Click;
                    customButton.PreviewMouseUp += PageManage_PreviewMouseUp;
                    //Label lb = new Label
                    //{
                    //    Content = item.resources_name,
                    //    HorizontalAlignment = HorizontalAlignment.Center
                    //};
                    //stack.Children.Add(customButton);
                    //stack.Children.Add(lb);
                    images.Children.Add(customButton);
                    planModel.ResourceCount++;
                    //images.Children.Add(stack);

                }
            }
        }

        public void UpdateImg4(List<resBKCategoryCourseChildModel> list)
        {
            if (list != null)
            {
                //tip0.Visibility = Visibility.Collapsed;
                //tip1.Visibility = Visibility.Visible;
                //images.Children.Clear();
                foreach (var item in list)
                {
                    CustomButton customButton = new CustomButton()
                    {
                        Template = (ControlTemplate)FindResource("selectedImageTemplate2"),
                        ImageSource = new BitmapImage(new Uri(item.image)),
                        Width = 180,
                        Height = 180,
                        BkResId = item.id.ToString(),
                        BkzyType = 3,

                        Margin = new Thickness(-10, 0, 0, 0),
                        Content = item.resources_name
                    };
                    customButton.MouseDoubleClick += CustomButtonDouble_Click;
                    customButton.PreviewMouseUp += PageManage_PreviewMouseUp;
                    images.Children.Add(customButton);
                    planModel.ResourceCount++;
                    //images.Children.Add(stack);
                }
            }
        }

        public void UpdateImg3(List<ReqGroupFileListDetialModel> list)
        {
            if (list != null)
            {
                //tip0.Visibility = Visibility.Collapsed;
                //tip1.Visibility = Visibility.Visible;
                //images.Children.Clear();
                foreach (var item in list)
                {
                    //string _url = item.file;
                    //switch (item.ext_name)
                    //{
                    //    case "pdf": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/pdf.png"; break;
                    //    case "mp4": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/mp4.png"; break;
                    //    case "doc": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/doc.png"; break;
                    //    case "docx": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/doc.png"; break;
                    //    case "mp3": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/mp3.png"; break;
                    //    case "ppt": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/ppt.png"; break;
                    //    case "pptx": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/ppt.png"; break;
                    //    case "swf": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/swf.png"; break;
                    //    case "txt": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/txt.png"; break;
                    //    case "xls": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/xls.png"; break;
                    //    case "xlsx": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/xls.png"; break;
                    //    case "zip": _url = "pack://application:,,,/HuiZe.education;component/Ethan/Res/Images/MySpace/zip.png"; break;
                    //}

                    //ControlTemplate _template = (ControlTemplate)FindResource("selectedImageTemplate_Ethan_MyLesson");
                    //CustomButton customButton = new CustomButton()
                    //{
                    //    Tag = item,
                    //    Width = 140,
                    //    Height = 130,
                    //    BkzyType = 2,
                    //    Content = item.file_name,
                    //    Margin = new Thickness(0, 0, 14, 14),
                    //    BkResId = item.id.ToString(),
                    //    ImageWidth = 140,
                    //    ImageHeight = 84,
                    //    ImageSource = new BitmapImage(new Uri(_url)),
                    //    Template = _template,//(ControlTemplate)FindResource("selectedImageTemplate2"),
                    //};

                    //((CustomButton)_template.FindName("deleteButton", customButton)).Click += RemoveLessonItem_Click;
                    //customButton.MouseDoubleClick += CustomButtonDouble_Click;
                    //customButton.PreviewMouseUp += PageManage_PreviewMouseUp;
                    //images.Children.Add(customButton);
                    //planModel.ResourceCount++;
                    //AppendAddResourceButton();

                    var _model = new resCourseListChildModel
                    {
                        type_token = 2,
                        id = item.id,
                        resources_name = item.file_name,
                        file = item.file,
                        file_size = item.file_size,
                        ext_name = item.ext_name,
                    };
                    planModel.EthanMyPackageList.Add(_model);
                    PART_MyLesson_Item _item_mylesson = new PART_MyLesson_Item();
                    _item_mylesson.DeleteCallback = DeleteLessonMedia;
                    _item_mylesson.SelectCallback = ShowLessonMedia;
                    _item_mylesson.Data = _model;
                    images.Children.Add(_item_mylesson);
                    planModel.ResourceCount++;
                }
                AppendAddResourceButton();
            }
        }

        public void UpdateImg5(List<ResResBkDetailModel> list)
        {
            if (list != null)
            {
                foreach (var item in list)
                {
                    var _model = new resCourseListChildModel
                    {
                        type_token = Convert.ToInt32(item.type),
                        id = item.id,
                        resources_name = item.bname,
                        file = item.file,
                        lyric = item.lyric,
                        lyric_text = item.lyric_text,
                        rotation_img = item.rotation_img,
                        ext_name = item.extname,
                        cover = item.image_cover,
                    };
                    planModel.EthanMyPackageList.Add(_model);
                    PART_MyLesson_Item _item_mylesson = new PART_MyLesson_Item();
                    _item_mylesson.DeleteCallback = DeleteLessonMedia;
                    _item_mylesson.SelectCallback = ShowLessonMedia;
                    _item_mylesson.Data = _model;
                    images.Children.Add(_item_mylesson);
                    planModel.ResourceCount++;
                }
                AppendAddResourceButton();
            }
        }

        void RemoveLessonItem_Click(object sender, RoutedEventArgs e)
        {

        }

        private void PageManage_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            //ShowLessonMedia(((CustomButton)sender).Tag as ReqGroupFileListDetialModel);
            //CustomButton Custombutton0 = sender as CustomButton;
            //CustomButton Custombutton = e.OriginalSource as CustomButton;
            //if (Custombutton.ImageSource.ToString().Contains("minClose.png"))
            //{
            //    var personCenterViewModel = DataContext as PlanLessonViewModel;
            //    string Id = Custombutton0.BkResId;
            //    string bkzyType = Custombutton0.BkzyType.ToString();
            //    personCenterViewModel.RemoveBkRes(bkzyType, Id);
            //    planModel.ResourceCount--;
            //}
        }

        private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var personCenterViewModel = DataContext as PlanLessonViewModel;
            personCenterViewModel.SelectClass2(e.NewValue);
        }

        //private void treeView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    var personCenterViewModel = DataContext as PlanLessonViewModel;
        //    var list = treeView.ItemsSource;
        //}

        private void CustomButtonDouble_Click(object sender, RoutedEventArgs e)
        {
            //ShowLessonMedia(((CustomButton)sender).Tag as ReqGroupFileListDetialModel);

            //PlanLessonViewModel model = DataContext as PlanLessonViewModel;
            //CustomButton customButton = sender as CustomButton;
            //string BkId = customButton.BkResId;
            //string bkzyType = customButton.BkzyType.ToString();
            //model.ShowResDetail(bkzyType, BkId);
        }

        void AppendAddResourceButton()
        {
            if (images.Children.Count > 0)
            {
                for (int i = 0; i < images.Children.Count; i++)
                {
                    if (images.Children[i] is CustomButton)
                        images.Children.Remove(images.Children[i]);
                }
            }
            images.Children.Add(AddResourceButton());
            Refresh_Title();
        }

        void DeleteLessonMedia(resCourseListChildModel _model)
        {
            if (_model == null) return;
            for (int i = 0; i < images.Children.Count; i++)
            {
                if (images.Children[i] is PART_MyLesson_Item)
                {
                    PART_MyLesson_Item _item_mylesson = (PART_MyLesson_Item)images.Children[i];
                    if (_item_mylesson.Data.id == _model.id)
                    {
                        images.Children.Remove(_item_mylesson);
                        planModel.EthanMyPackageList.Remove(_model);
                        Refresh_Title();
                        return;
                    }
                }
            }
        }

        void ShowLessonMedia(resCourseListChildModel _model)
        {
            Win_Lesson_MyPackage_Viewer _win = new Win_Lesson_MyPackage_Viewer();
            _win.Owner = Application.Current.MainWindow;
            _win.Loaded += (sender, e) =>
            {
                _win.Load(planModel.EthanMyPackageList, _model.id);
            };
            _win.ShowDialog();
        }

        void Refresh_Title()
        {
            if (images.Children.Count > 1)
            {
                BkTitleLabel.Text = "全部资源";
                BkTitleLabel.Text = planModel.BKTitle;
                PART_Title.Text = $"已添加{images.Children.Count - 1}个资源，拖动缩略图进行排序";
            }
            else
            {
                BkTitleLabel.Text = "未选择备课章节，请从右侧课程资源选择备课章节";
                PART_Title.Text = "从右侧\"课程资源\"或\"资源中心\"、\"我的空间\"中选择您需要的课件，自由进行排列组合，灵活备课";
            }
        }

        CustomButton AddResourceButton()
        {
            return new CustomButton
            {
                Tag = -1,
                Width = 140,
                Height = 130,
                Margin = new Thickness(0, 0, 14, 14),
                Content = "添加资源",
                Command = planModel.SelectChapterCommand,
                Template = (ControlTemplate)FindResource("AddplanLessonTemplate_Ethan"),

            };
        }

        T FindVisualParent<T>(DependencyObject _obj) where T : class
        {
            while (_obj != null)
            {
                if (_obj is T)
                    return _obj as T;

                _obj = VisualTreeHelper.GetParent(_obj);
            }
            return null;
        }
    }
}
